<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useSettingsStore } from '../stores/settings'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { SyncConfig, SyncConfigInput } from '../types/electron'

// 设置存储
const settingsStore = useSettingsStore()

// 同步配置列表
const syncConfigs = ref<SyncConfig[]>([])
const isLoading = ref(false)
const newConfig = ref<SyncConfigInput>({
  provider: 'onedrive',
  name: '',
  config: {
    clientId: '',
    redirectUri: '',
    scope: 'Files.ReadWrite'
  }
})

// 初始化
onMounted(async () => {
  // 初始化设置
  await settingsStore.initSettings()
  
  // 加载同步配置
  await loadSyncConfigs()
})

// 加载同步配置
const loadSyncConfigs = async () => {
  isLoading.value = true
  
  try {
    syncConfigs.value = await window.elec.sync.getConfigs()
  } catch (error) {
    console.error('加载同步配置失败', error)
    ElMessage.error('加载同步配置失败')
  } finally {
    isLoading.value = false
  }
}

// 保存同步配置
const saveConfig = async () => {
  if (!newConfig.value.name.trim()) {
    ElMessage.warning('请输入配置名称')
    return
  }
  
  try {
    await window.elec.sync.saveConfig(newConfig.value)
    ElMessage.success('保存成功')
    
    // 重置表单
    newConfig.value = {
      provider: 'onedrive',
      name: '',
      config: {
        clientId: '',
        redirectUri: '',
        scope: 'Files.ReadWrite'
      }
    }
    
    // 重新加载配置
    await loadSyncConfigs()
  } catch (error) {
    console.error('保存同步配置失败', error)
    ElMessage.error('保存同步配置失败')
  }
}

// 设置活动配置
const setActiveConfig = async (id: number) => {
  try {
    await window.elec.sync.setActive(id)
    ElMessage.success('设置成功')
    
    // 更新本地状态
    syncConfigs.value = syncConfigs.value.map(config => ({
      ...config,
      is_active: config.id === id ? 1 : 0
    }))
    
    // 更新同步启用状态
    await settingsStore.setSyncEnabled(true)
  } catch (error) {
    console.error('设置活动配置失败', error)
    ElMessage.error('设置活动配置失败')
  }
}

// 删除配置
const deleteConfig = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该同步配置吗？',
      '删除配置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await window.elec.sync.deleteConfig(id)
    ElMessage.success('删除成功')
    
    // 重新加载配置
    await loadSyncConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除同步配置失败', error)
      ElMessage.error('删除同步配置失败')
    }
  }
}

// 启动同步
const startSync = async () => {
  if (!settingsStore.syncEnabled) {
    ElMessage.warning('请先启用同步')
    return
  }
  
  try {
    const result = await window.elec.sync.startSync()
    ElMessage.success(result.message)
  } catch (error) {
    console.error('同步失败', error)
    ElMessage.error('同步失败')
  }
}
</script>

<template>
  <div class="settings-page">
    <div class="settings-container">
      <h1>设置</h1>
      
      <!-- 主题设置 -->
      <div class="settings-section">
        <h2>界面设置</h2>
        
        <div class="settings-item">
          <span class="settings-label">主题</span>
          <el-select v-model="settingsStore.theme" @change="settingsStore.setTheme">
            <el-option label="系统" value="system" />
            <el-option label="亮色" value="light" />
            <el-option label="暗色" value="dark" />
          </el-select>
        </div>
        
        <div class="settings-item">
          <span class="settings-label">字体大小</span>
          <el-input-number 
            v-model="settingsStore.fontSize" 
            :min="12" 
            :max="20" 
            @change="settingsStore.setFontSize" 
          />
        </div>
        
        <div class="settings-item">
          <span class="settings-label">行高</span>
          <el-input-number 
            v-model="settingsStore.lineHeight" 
            :min="1.2" 
            :max="2.0" 
            :step="0.1" 
            :precision="1"
            @change="settingsStore.setLineHeight" 
          />
        </div>
      </div>
      
      <!-- 编辑器设置 -->
      <div class="settings-section">
        <h2>编辑器设置</h2>
        
        <div class="settings-item">
          <span class="settings-label">默认编辑模式</span>
          <el-select v-model="settingsStore.editorMode" @change="settingsStore.setEditorMode">
            <el-option label="所见即所得" value="wysiwyg" />
            <el-option label="双栏模式" value="split" />
            <el-option label="源代码" value="tab" />
          </el-select>
        </div>
        
        <div class="settings-item">
          <span class="settings-label">显示行号</span>
          <el-switch 
            v-model="settingsStore.showLineNumbers" 
            @change="settingsStore.setShowLineNumbers" 
          />
        </div>
        
        <div class="settings-item">
          <span class="settings-label">自动保存</span>
          <el-switch 
            v-model="settingsStore.autoSave" 
            @change="settingsStore.setAutoSave" 
          />
        </div>
      </div>
      
      <!-- 同步设置 -->
      <div class="settings-section">
        <h2>同步设置</h2>
        
        <div class="settings-item">
          <span class="settings-label">启用同步</span>
          <el-switch 
            v-model="settingsStore.syncEnabled" 
            @change="settingsStore.setSyncEnabled" 
          />
        </div>
        
        <div class="settings-item">
          <el-button type="primary" @click="startSync" :disabled="!settingsStore.syncEnabled">
            立即同步
          </el-button>
        </div>
        
        <!-- 同步配置列表 -->
        <div class="sync-configs">
          <h3>同步配置</h3>
          
          <el-table :data="syncConfigs" v-loading="isLoading" style="width: 100%">
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="provider" label="类型">
              <template #default="{ row }">
                <el-tag>{{ row.provider === 'onedrive' ? 'OneDrive' : '自定义' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="is_active" label="状态">
              <template #default="{ row }">
                <el-tag :type="row.is_active === 1 ? 'success' : 'info'">
                  {{ row.is_active === 1 ? '活动' : '未激活' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button 
                  v-if="row.is_active === 0" 
                  type="primary" 
                  size="small" 
                  @click="setActiveConfig(row.id)"
                >
                  设为活动
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="deleteConfig(row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 添加新配置 -->
          <div class="add-config">
            <h3>添加新配置</h3>
            
            <div class="settings-item">
              <span class="settings-label">类型</span>
              <el-select v-model="newConfig.provider">
                <el-option label="OneDrive" value="onedrive" />
                <el-option label="自定义" value="custom" />
              </el-select>
            </div>
            
            <div class="settings-item">
              <span class="settings-label">名称</span>
              <el-input v-model="newConfig.name" placeholder="配置名称" />
            </div>
            
            <template v-if="newConfig.provider === 'onedrive'">
              <div class="settings-item">
                <span class="settings-label">Client ID</span>
                <el-input v-model="newConfig.config.clientId" placeholder="应用 Client ID" />
              </div>
              
              <div class="settings-item">
                <span class="settings-label">重定向 URI</span>
                <el-input v-model="newConfig.config.redirectUri" placeholder="重定向 URI" />
              </div>
              
              <div class="settings-item">
                <span class="settings-label">作用域</span>
                <el-input v-model="newConfig.config.scope" disabled />
              </div>
            </template>
            
            <template v-else>
              <div class="settings-item">
                <span class="settings-label">API 地址</span>
                <el-input v-model="newConfig.config.apiUrl" placeholder="API 地址" />
              </div>
              
              <div class="settings-item">
                <span class="settings-label">认证令牌</span>
                <el-input v-model="newConfig.config.token" placeholder="认证令牌" />
              </div>
            </template>
            
            <div class="settings-item">
              <el-button type="primary" @click="saveConfig">保存配置</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.settings-page {
  padding: 20px;
  height: 100%;
  overflow: auto;
}

.settings-container {
  max-width: 800px;
  margin: 0 auto;
}

.settings-section {
  margin-bottom: 30px;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid var(--border-color);
}

.settings-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.settings-label {
  width: 120px;
  margin-right: 10px;
}

.sync-configs {
  margin-top: 20px;
}

.add-config {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

h1 {
  margin-bottom: 20px;
}

h2 {
  font-size: 18px;
  margin-top: 0;
  margin-bottom: 15px;
}

h3 {
  font-size: 16px;
  margin-top: 0;
  margin-bottom: 15px;
}

/* 暗黑模式适配 */
.dark-mode .settings-section {
  border-color: #333;
  background-color: #1e1e1e;
}

.dark-mode .add-config {
  border-color: #333;
}
</style> 